/*
 * Copyright (C) 2010 Fred Bojin Liu.
 *
 * Licensed under the GPL, Version 2.0;
 * you may not use this file except in compliance with the License.
 * A copy of the license is included (see the "LICENSE.txt")
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package edu.ucdavis.fredliu.speedtracker;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import android.util.Log;

public class FileManager {
	public static final String TAG="FileManager_TAG";
	private String fileName;
	private File file;
	public FileManager(String name){
		fileName=name+System.currentTimeMillis()+".csv";
	}
	public boolean createFile(){
		Log.d(TAG, "Before creating the file");
		//create /sdcard/
		String name=fileName;
		File sdDir = new File("/sdcard/");
		if(sdDir.exists()&&sdDir.canWrite()){
			File appDir = new File(sdDir.getAbsolutePath()+"/SpeedTracker");
			appDir.mkdir();
			if(appDir.exists()&&appDir.canWrite()){
				File traceFile = new File(appDir.getAbsolutePath()+"/"+name);
				try{
					traceFile.createNewFile();
				}catch(IOException ioe){
					Log.e(TAG, "Can't create the file");
					return false;
				}
				file=traceFile;
				return true;
			}else{
				return false;
			}
		}else{
			return false;
		}
		
	}

	/**
	 * 
	 * @param str: String to be written if the file exist
	 * @return: true if written succesfully, false otherwise
	 */
	public boolean write(String str){
		//Log.d(TAG, "Before Writing the file");
		if (file==null) 
			return false;
		if(file.exists()&&file.canWrite()){
			PrintWriter writer = null;
			try{
				writer = new PrintWriter(new FileWriter(file.getAbsolutePath(),true));
				writer.append(str+'\n');
//				writer.println(str);
				writer.flush();
				writer.close();
				return true;
				//writer..write(str.getBytes());
			}catch(FileNotFoundException e){
				Log.e(TAG, "File not found");
				return false;
			} catch (IOException e) {
				Log.e(TAG,"IOException");
				return false;
			}
		}else{
			return false;
		}
	}

}
